'''
https://leetcode.cn/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
'''
from collections import deque
from typing import List


class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        n = len(nums)
        ans = 0
        max_queue = deque()  # 从左往右，从大到小； q[0]最大值
        min_queue = deque()  # 从左往右，从小到大； q[0]最小值
        l, r = 0, 0
        while r < n:
            while max_queue and nums[r] >= nums[max_queue[-1]]:
                max_queue.pop()
            while min_queue and nums[r] <= nums[min_queue[-1]]:
                min_queue.pop()
            max_queue.append(r)
            min_queue.append(r)

            while l < r and max_queue and nums[max_queue[0]] - nums[min_queue[0]] > limit:
                if max_queue[0] == l:
                    max_queue.popleft()
                if min_queue[0] == l:
                    min_queue.popleft()
                l += 1
            # print(l, r, max_queue, min_queue)
            ans = max(ans, r - l + 1)
            r += 1
        return ans
